package com.ting.template.core.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.DateConverter;

/**
 * <p>Bean转换工具类</p>
 * @author gongjiaming
 * @version $Id: BeanConverterUtil.java, v 0.1 2017年6月14日 下午5:56:36 雷霆 Exp $
 */
public class BeanConverterUtil extends BeanUtils {

	private static final BigDecimal BIGDECIMAL_ZERO = new BigDecimal("0");
	static {
		ConvertUtils.register(new DateConverter(new Date()), java.util.Date.class);
		BigDecimalConverter bd = new BigDecimalConverter(BIGDECIMAL_ZERO);
		ConvertUtils.register(bd, java.math.BigDecimal.class);
	}

	public static void copyProperties(Object target, Object source) throws InvocationTargetException, IllegalAccessException {
		org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T mapToObject( Map map, Class<?> bean) throws Exception{    
        if (map == null)  
            return null;  
        Object obj = bean.newInstance();  
        org.apache.commons.beanutils.BeanUtils.populate(obj, map);  
        return (T) obj;  
    }    
      
    @SuppressWarnings("rawtypes")
	public static Map objectToMap(Object obj) throws Exception{  
        if(obj == null)  
            return null;   
        return org.apache.commons.beanutils.BeanUtils.describe(obj);  
    }    
}
